/**
 *  @author Morozan Ion
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.dddforandroid.servlets;

import java.io.IOException;

import javax.jdo.PersistenceManager;
import javax.jdo.Transaction;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dddforandroid.classes.NotePad.Notes;
import com.dddforandroid.crud.PMF;
import com.dddforandroid.util.Util;
import com.google.appengine.api.NamespaceManager;

@SuppressWarnings("serial")
public class DeleteOrUpdate extends HttpServlet {

	/**
	 * Handles the HTTP <code>GET</code> method.
	 * 
	 * @param req
	 *            servlet request
	 * @param resp
	 *            servlet response
	 * @throws ServletException
	 *             if a servlet-specific error occurs
	 * @throws IOException
	 *             if an I/O error occurs
	 */
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		String color = req.getParameter("color");
		System.out.println("TRECE AICI GET  " + color);

		getServletContext().getRequestDispatcher("/").forward(req, resp);
	}

	/**
	 * Handles the HTTP <code>POST</code> method.
	 * 
	 * @param request
	 *            servlet request
	 * @param response
	 *            servlet response
	 * @throws ServletException
	 *             if a servlet-specific error occurs
	 * @throws IOException
	 *             if an I/O error occurs
	 */
	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		/* Id of the object */
		String DeleteId = request.getParameter("delete");
		String UpdateId = request.getParameter("update");
		
		/** Get information about current logged in user id*/
		Util user = new Util();
		/** Create a namespace for current loggedin user. */
		NamespaceManager.set(user.getUserId());
		
		/** getting the instance of the database */
		PersistenceManager db = PMF.get().getPersistenceManager();

		/** keep database consistent */
		Transaction transaction = db.currentTransaction();
		
		/** if delete button was pressed */
		if (null != DeleteId) {
			/* for the given ID */
			try {
				try {
					transaction.begin();
					/* Delete desired note from DB */
					db.deletePersistent(db.getObjectById(Notes.class, DeleteId));
					transaction.commit();
				} catch (Exception ex) {
					/* if smth went wrong */
					if (transaction.isActive()) {
						transaction.rollback();
					}
				}
			} finally {
				/* close the DB in a consistent state */
				db.close();
			}
			response.setHeader("Refresh", "1");
			response.sendRedirect("/");
		} else {			
			/* for the given ID */
			try {
				try {
					transaction.begin();
					/* Get desired Note from DB */
					Notes note = db.getObjectById(Notes.class, UpdateId);
					transaction.commit();
					
					/** Set the content of the note into Add task form for editing */
					request.setAttribute("title", note.getTitle());
					request.setAttribute("note", note.getNote());
					request.setAttribute("id", note.getId());
					
					RequestDispatcher rd = request.getRequestDispatcher("/");
					rd.forward(request, response);
					
				} catch (Exception ex) {
					/* if smth went wrong */
					if (transaction.isActive()) {
						transaction.rollback();
					}
				}
			} finally {
				/* close the DB in a consistent state */
				db.close();
			}
		}
	}
}
